package cn.itcast.hotel.service.impl;

import ch.qos.logback.core.net.server.Client;
import cn.itcast.hotel.conf.RestHighClient;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {

        //分页
        int page = params.getPage(),size = params.getSize();
        SearchRequest request = new SearchRequest("hotel");
        request.source().from((page-1)*size)
                .size(size);

        //准备query
        buildBasicQuery(params,request);

        //根据location排序
        String location = params.getLocation();

        if (!Strings.isEmpty(location)){
        request.source().sort(SortBuilders.geoDistanceSort("location",new GeoPoint(location))
                .order(SortOrder.ASC)
                .unit(DistanceUnit.KILOMETERS));
        }
        //发送请求
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public Map<String,List<String>> filters(RequestParams params){
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("hotel");
            // 2.准备DSL
            // 2.1.query
            buildBasicQuery(params, request);
            // 2.2.设置size
            request.source().size(0);
            // 2.3.聚合
            buildAggregation(request);
            // 3.发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            List<String> cityList = getAggByName(aggregations, "cityAgg");
            result.put("city", cityList);
            // 4.1.根据品牌名称，获取品牌结果
            // 4.3.根据品牌名称，获取品牌结果
            List<String> starList = getAggByName(aggregations, "starAgg");
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            result.put("brand", brandList);
            // 4.2.根据品牌名称，获取品牌结果
            result.put("starName", starList);

            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("cityAgg")
                .field("city")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("starAgg")
                .field("starName")
                .size(100)
        );
    }

    @Override
    public List<String> getSuggestions(String prefix) {

        //准备request
        try{
        SearchRequest request = new SearchRequest("hotel");
        //准备DSL
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "suggestion",
                SuggestBuilders.completionSuggestion("suggestion")
                        .prefix(prefix)
                        .size(10)
                        .skipDuplicates(true)
                ));

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        Suggest suggest = response.getSuggest();
        CompletionSuggestion suggestion = suggest.getSuggestion("suggestion");
        List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
        // 4.3.遍历
        List<String> list = new ArrayList<>(options.size());
        for (CompletionSuggestion.Entry.Option option : options) {
            String text = option.getText().toString();
            list.add(text);
        }
        return list;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    }

    private void buildBasicQuery(RequestParams params , SearchRequest request){
        //构建booleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //获取params的参数
        String key = params.getKey(),
                city = params.getCity(),
                brand = params.getBrand(),
                startName = params.getStarName(),
                maxPrice = String.valueOf(params.getMaxPrice()),
                minPrice = String.valueOf(params.getMinPrice());

        //关键字搜索
        if (!Strings.isEmpty(key)){
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }

        if (!Strings.isEmpty(city)) {boolQuery.filter(QueryBuilders.termQuery("city",city));}
        if (!Strings.isEmpty(brand)) {boolQuery.filter(QueryBuilders.termQuery("brand",brand));}
        if (!Strings.isEmpty(startName)){ boolQuery.filter(QueryBuilders.termQuery("starName",startName));}
        if (params.getMinPrice() != null && params.getMaxPrice() != null){ System.err.println("keyi");}
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));}

        // 2.算分控制
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQuery,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });




        request.source().query(functionScoreQuery);
    }

private PageResult handleResponse(SearchResponse response) {
        //响应解析
        SearchHits searchHits = response.getHits();
        //获取总条数
        long total = searchHits.getTotalHits().value;
        //文档数组
        SearchHit[] hits = searchHits.getHits();
        //遍历并放入集合
        List<HotelDoc> list = Arrays.stream(hits)
                .map(hit -> {
                    String json = hit.getSourceAsString();

                    HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
                    if (hit.getSortValues().length != 0 ){
                        hotelDoc.setDistance(hit.getSortValues()[0]);
                    }
                    return hotelDoc;

                })
                .collect(Collectors.toList());

        System.out.println(list);
        System.out.println("共查询到" + total + "条数据");
        return new PageResult(total, list);
    }



    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3.遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }
}
